package cn.edu.zufe.mjt;


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 蒙锦涛
 * @date 2025/6/6
 */


public class MyInterfaceFactory {

	private static final AtomicInteger count = new AtomicInteger();

	private static File createJavaFile(String className, MyHandler handler) throws IOException {
		String function1 = handler.functionBody("func1");
		String function2 = handler.functionBody("func2");
		String function3 = handler.functionBody("func3");
		String context = "package cn.edu.zufe.mjt;\n" +
				"\n" +
				"public class " + className + " implements MyInterface{\n" +
				"\t" + "private MyInterface myInterface;\n" +
				"\t@Override\n" +
				"\tpublic void func1() {\n" +
				"\t" + function1 + "\n" +
				"\t}\n" +
				"\n" +
				"\t@Override\n" +
				"\tpublic void func2() {\n" +
				"\t" + function2 + "\n" +
				"\t}\n" +
				"\n" +
				"\t@Override\n" +
				"\tpublic void func3() {\n" +
				"\t" + function3 + "\n" +
				"\t}\n" +
				"}\n";
		// 获取当前工作目录（即模块根目录）
		String moduleRoot = System.getProperty("user.dir");

		// 构建目标文件路径：模块根目录 + 文件名
		File javaFile = new File(moduleRoot, className + ".java");
		Files.writeString(javaFile.toPath(), context);
		return javaFile;
	}

	private static String getClassName() {
		return "MyInterface$proxy" + count.incrementAndGet();
	}

	private static MyInterface newInstance(String className, MyHandler handler) throws Exception {
		Class<?> aClass = MyInterfaceFactory.class.getClassLoader().loadClass(className);
		Constructor<?> constructor = aClass.getConstructor();
		MyInterface proxy = (MyInterface) constructor.newInstance();
		handler.setProxy(proxy);
		return proxy;
	}

	public static MyInterface createProxy(MyHandler handler) throws Exception {
		String className = getClassName();
		File javaFile = createJavaFile(className, handler);
		Compiler.compile(javaFile);
		return newInstance("cn.edu.zufe.mjt." + className, handler);
	}


}
